<template>
  <view class="login-box">
    <uni-icons type="contact" size="100" color="#AFAFAF"></uni-icons>
    <button open-type="getUserInfo" @getuserinfo="getUserinfo" type="primary" class="btn-login">一键登录</button>
    <text class="text">登录后尽享更多权益</text>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  export default {
    name: "my-login",
    data() {
      return {

      };
    },
    computed: {
      ...mapState('my_user', ['redirectInfo'])
    },
    methods: {
      ...mapMutations('my_user', ['updataUserinfo', 'updataToken', 'updataRedirectInfo']),
      getUserinfo(e) {
        if (e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('你取消了授权，登录失败')
        // console.log(e.detail.userInfo)
        this.updataUserinfo(e.detail.userInfo)
        this.getToken(e.detail)
      },
      async getToken(info) {
        // 调用微信登录接口
        const [err, res] = await uni.login().catch(err => err)
        // 判断是否 uni.login() 调用失败

        if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！' + err)

        const query = {
          code: res.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        }
        // console.log(query);

        const {
          data: loginResult
        } = await uni.$http.post('/api/public/v1/users/wxlogin', query)
        console.log(loginResult)
        if (loginResult.meta.status !== 200) return uni.$showMsg('登录失败！')
        //  更新 vuex 中的 token
        this.updateToken(loginResult.message.token)
        this.navigateBack()
      },
      navigateBack() {
        if (this.redirectInfo && this.redirectInfo.openType === 'switchTab') {
          uni.switchTab({
            url: this.redirectInfo.from,
            complete() {
              this.updataRedirectInfo(null)
            }
          })
        }
      }

    }
  }
</script>

<style lang="scss">
  .login-box {
    position: relative;
    overflow: hidden;

    &::after {
      content: '';
      display: block;
      position: absolute;
      left: 0;
      bottom: 0;
      transform: translateY(50%);
      border-radius: 100%;
      width: 100%;
      height: 50px;
      background-color: #f5f5f5;

    }

    width: 100%;
    height: 750rpx;
    display: flex;
    background-color: #aaffff;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .btn-login {
      width: 90%;
      border-radius: 50px;
    }

    .text {
      margin-top: 10px;
      color: #85868a;
      font-size: 12px;
    }
  }
</style>
